<template>
  <a-card :bordered="false" class="br-10">
    <div class="deptStaff-content">
      <div class="tree-box">
        <v-jstree
          :data="data"
          :item-events="itemEvents"
          allow-batch
          @item-click="itemClick"
          @item-drag-start="itemDragStart"
          @item-drag-end="itemDragEnd"
          @item-drop-before="itemDropBefore"
          @item-drop="itemDrop"
        >
          <template slot-scope="_">
            <div style="display: inherit;" @click.ctrl="customItemClickWithCtrl">
              <i :class="_.vm.themeIconClasses" role="presentation" v-if="!_.model.t"></i>
              {{ _.model.deptName }}
              <span>
                <button
                  style="border: 0px; background-color: transparent; cursor: pointer;"
                  @click="handleAdd(_.vm, _.model, $event)"
                >
                  <i class="fa fa-plus-square-o"></i>
                </button>
                <button
                  v-if="_.model.type === 1"
                  style="border: 0px; background-color: transparent; cursor: pointer;"
                  @click="handleEdit(_.vm, _.model, $event)"
                >
                  <i class="fa fa-edit"></i>
                </button>
                <button
                  v-if="_.model.type === 1"
                  style="border: 0px; background-color: transparent; cursor: pointer;"
                  @click="handleDel(_.vm, _.model, $event)"
                >
                  <i class="fa fa-trash-o"></i>
                </button>
              </span>
            </div>
          </template>
        </v-jstree>
      </div>
      <div class="table-right">
        <div class="table-page-search">
          <a-form>
            <a-form-item label="姓名">
              <a-input placeholder="请输入" v-model="queryParam.keyword" />
            </a-form-item>
            <span class="search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button @click="() => (queryParam.keyword = undefined)">重置</a-button>
            </span>
          </a-form>
        </div>
        <div class="table-operator disFlxJS">
          <div>
            <a-button type="primary" @click="handleStaffAdd">新建</a-button>
            <a-button type="danger" @click="delByIds(ids)">批量删除</a-button>
            <a-button @click="templateDown">下载模板</a-button>
            <a-upload
              name="file"
              :customRequest="upload"
              :headers="headers"
              :before-upload="beforeUpload"
              :showUploadList="false"
            >
              <a-button>导入</a-button>
            </a-upload>
            <a-button @click="excelDown">导出</a-button>
          </div>
          <CustomTable :name="$route.name" :columns="columns" :newColumns="newColumns" />
        </div>
        <s-table
          size="default"
          ref="table"
          rowKey="id"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="newColumns"
          :data="loadData"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ (pageNum - 1) * pageSize + index + 1 }}
          </span>
          <span slot="avatar" slot-scope="text, record">
            <a-avatar v-if="record.avatar !== ''" :src="record.avatar" />
            <a-avatar v-else icon="user" />
          </span>
          <span slot="action" slot-scope="text, record">
            <a-button type="primary" ghost size="small" class="_mr-5" @click="handleStaffEdit(record)">
              编辑
            </a-button>
            <a-button type="primary" ghost size="small" class="_mr-5" @click="delByIds([record.id])">
              删除
            </a-button>
          </span>
        </s-table>
      </div>
    </div>
    <dept-form ref="deptForm" @ok="handleDeptList" />
    <staff-form ref="staffForm" @add="$refs.table.refresh(true)" @upd="$refs.table.refresh()" />
  </a-card>
</template>
<script>
import { STable } from '@/components'
import VJstree from 'vue-jstree'
import {
  deptList,
  deptRemove,
  staffExportExcel,
  staffImportExcel,
  staffList,
  staffRemove,
  staticExcel
} from '@/api/system/system'
import { TabtreeData } from '@/utils/treeutil'
import { mimeMap, readAsText, resolveBlob } from '@/utils/download'
import deptForm from './modules/deptForm'
import staffForm from './modules/staffForm'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANTID } from '@/store/mutation-types'
import CustomTable from '@/components/Cuscolumn'

export default {
  data() {
    return {
      headers: {
        token: Vue.ls.get(ACCESS_TOKEN),
        tenantId: Vue.ls.get(TENANTID)
      },
      queryParam: {
        deptId: ''
      },
      // 表头
      columns: [
        {
          title: '工号',
          dataIndex: 'code',
          width: '100px',
          ellipsis: true
        },
        {
          title: '账号',
          dataIndex: 'loginName',
          width: '100px',
          ellipsis: true
        },
        {
          title: '照片',
          dataIndex: 'avatar',
          width: '100px',
          scopedSlots: { customRender: 'avatar' }
        },
        {
          title: '姓名',
          dataIndex: 'name',
          width: '120px'
        },
        {
          title: '联系电话',
          dataIndex: 'tel',
          width: '150px',
          ellipsis: true
        },
        {
          title: '电子邮件',
          dataIndex: 'email',
          width: '180px',
          ellipsis: true
        },
        {
          title: '组织名称',
          dataIndex: 'orgName',
          width: '100px',
          ellipsis: true
        },
        {
          title: '部门名称',
          dataIndex: 'deptName',
          width: '100px',
          ellipsis: true
        },
        {
          title: '职务名称',
          dataIndex: 'postName',
          width: '100px',
          ellipsis: true
        },
        {
          title: '入职日期',
          dataIndex: 'hireDate',
          width: '150px',
          ellipsis: true
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: '100px',
          ellipsis: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '120px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      selectedRowKeys: [],
      selectedRows: [],
      ids: [],
      pageNum: 1,
      pageSize: 10,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        var params = {
          current: parameter.pageNum,
          size: parameter.pageSize
        }
        return staffList(Object.assign(params, this.queryParam)).then(res => {
          this.pageNum = parameter.pageNum
          this.pageSize = parameter.pageSize
          this.selectedRowKeys = []
          this.selectedRows = []
          this.ids = []
          return res
        })
      },
      itemEvents: {
        mouseover: function() {
          console.log('mouseover')
        },
        contextmenu: function() {
          console.log(arguments[2])
          arguments[2].preventDefault()
          console.log('contextmenu')
        }
      },
      data: [],
      deptData: []
    }
  },
  computed: {
    newColumns() {
      const currentColumns = this.$store.state.user.customTable;
      if (currentColumns && currentColumns[this.$route.name]) {
        return this.$options.data().columns.filter(v => {
          const _items = currentColumns[this.$route.name].find((item) => item === v.title || item.title === v.title);
          if(_items) return Object.assign(v,_items)
        }).sort((a,b)=>{return a.tableSort - b.tableSort})
      } else {
        return this.columns
      }
    }
  },
  created() {
    this.handleDeptList()
  },
  components: {
    VJstree,
    STable,
    deptForm,
    staffForm,
    CustomTable
  },
  methods: {
    // 获取部门
    handleDeptList() {
      return deptList().then(res => {
        if (res.code === 0) {
          var arr = JSON.parse(JSON.stringify(res.data))
          for (var arrItem of arr) {
            arrItem.title = arrItem.deptName
            arrItem.value = arrItem.deptId
            arrItem.key = arrItem.deptId
            if (arrItem.type === 0) {
              arrItem.disabled = true
            }
          }
          this.deptData = TabtreeData(arr, 'deptId', 'parentId', 'children', '0')
          for (var item of res.data) {
            item.loading = false
            item.opened = true
            if (item.deptId === this.queryParam.deptId) {
              item.selected = true
            } else {
              item.selected = false
            }
            if (item.type === 0) {
              item.icon = 'fa fa-university'
            } else {
              item.icon = 'fa fa-users'
            }
          }
          this.data = TabtreeData(res.data, 'deptId', 'parentId', 'children', '0')
          console.log(this.data)
        }
      })
    },

    // 点击展开、收缩
    customItemClickWithCtrl(node, item, e) {
      console.log(node, item, e)
    },

    itemClick(node, item, draggedItem) {
      if (this.queryParam.deptId === item.deptId) {
        item.selected = false
        this.queryParam.deptId = ''
      } else {
        item.selected = true
        this.queryParam.deptId = item.deptId
      }
      this.$refs.table.refresh(true)
      console.log(node, item, draggedItem)
    },
    itemDragStart(node) {
      console.log(node.model.text + ' drag start !')
    },
    itemDragEnd(node) {
      console.log(node.model.text + ' drag end !')
    },
    itemDropBefore(node, item, draggedItem, e) {
      if (!draggedItem) {
        item.addChild({
          text: 'newNode',
          value: 'newNode'
        })
      }
    },
    itemDrop(node, item, draggedItem, e) {
      var sortBy = function(attr, rev) {
        if (rev === undefined) {
          rev = 1
        } else {
          rev = rev ? 1 : -1
        }
        return function(a, b) {
          a = a[attr]
          b = b[attr]
          if (a < b) {
            return rev * -1
          }
          if (a > b) {
            return rev * 1
          }
          return 0
        }
      }
      item.children.sort(sortBy('text', true))
      this.$refs.tree.handleRecursionNodeChildren(draggedItem, function(childrenItem) {
        childrenItem.selected = item.selected
      })
      console.log(node.model.text + ' drop !')
    },

    // 添加部门
    handleAdd(node, item, e) {
      e.stopPropagation()
      console.log(node, item)
      var params = {
        type: 'add',
        title: '新增部门',
        data: { parentId: item.deptId }
      }
      this.$refs.deptForm.add(params)
    },

    // 编辑部门
    handleEdit(node, item, e) {
      e.stopPropagation()
      var obj = JSON.parse(JSON.stringify(item))
      obj.parentId = item.deptId
      var params = {
        type: 'edit',
        title: '编辑部门',
        data: obj
      }
      this.$refs.deptForm.edit(params)
    },

    // 删除部门
    handleDel(node, item, e) {
      e.stopPropagation()
      var _this = this
      this.$confirm({
        title: '删除部门',
        content: '是否确定删除该部门?',
        onOk() {
          var params = {
            deptId: item.deptId
          }
          return deptRemove(params).then(res => {
            if (res.code === 0) {
              _this.$message.success('删除成功!')
              var index = node.parentItem.indexOf(item)
              node.parentItem.splice(index, 1)
            } else {
              _this.$message.error(res.msg)
            }
          })
        },
        onCancel() {}
      })
    },

    // 新建员工
    handleStaffAdd() {
      var params = {
        title: '新建员工',
        type: 'add',
        dept: JSON.parse(JSON.stringify(this.deptData)),
        data: {}
      }
      this.$refs.staffForm.add(params)
    },

    // 编辑员工
    handleStaffEdit(obj) {
      var params = {
        title: '编辑员工',
        type: 'edit',
        dept: JSON.parse(JSON.stringify(this.deptData)),
        data: obj
      }
      this.$refs.staffForm.edit(params)
    },

    // 批量删除
    delByIds(ids) {
      if (ids.length <= 0) {
        this.$message.warning('请选择员工')
        return false
      }
      var _this = this
      this.$confirm({
        title: '删除?',
        content: '是否确定删除该员工?',
        onOk() {
          staffRemove(ids).then(res => {
            if (res.code === 0) {
              _this.$message.success(`删除成功`)
              _this.$refs.table.refresh(true)
            } else {
              _this.$message.error(res.msg)
            }
          })
        },
        onCancel() {}
      })
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.ids = []
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (var item of selectedRows) {
        this.ids.push(item.id)
      }
    },

    // 下载模板
    templateDown() {
      var params = {
        templateName: '职员导入模板.xlsx'
      }
      staticExcel(params)
    },

    // 导出
    excelDown() {
      staffExportExcel(this.queryParam)
    },

    // 导入前校验
    beforeUpload(file) {
      const bool = file.type === mimeMap.xls || file.type === mimeMap.xlsx
      if (!bool) {
        this.$message.error('请上传excel文件!')
      }
      return bool
    },

    // 导入模板
    upload(params) {
      const file = params.file
      // 根据后台需求数据格式
      var form = new FormData()
      // 文件对象
      form.append('file', file)
      return staffImportExcel(form, this.orgType).then(res => {
        console.log('res.====', res.data.type)
        if (res.data.type === 'application/json') {
          readAsText(res.data).then(result => {
            if (result.code === 0) {
              this.$message.success('导入成功')
              this.$refs.table.refresh(true)
            } else {
              this.$message.error(result.msg)
            }
          })
        } else {
          this.$refs.table.refresh(true)
          resolveBlob(res, mimeMap.xlsx)
        }
      })
    }
  }
}
</script>
<style scope lang="less">
.deptStaff-content {
  display: flex;
  justify-content: left;
}

.tree-box {
  border: 1px solid #eeeeee;
  padding: 5px;
  border-radius: 5px;
  min-height: 560px;
  margin-right: 20px;
  width: 400px;
  overflow-x: auto;
  flex-shrink: 1;
}

.table-right {
  width: 100%;
  overflow: hidden;
}
</style>
